/**
 * Copyright &copy; 2015-2020 <a href="http://www.jeeplus.org/">JeePlus</a> All rights reserved.
 */
package com.jeeplus.modules.tms.web;

import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Random;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.ConstraintViolationException;

import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.google.common.collect.Lists;
import com.jeeplus.common.utils.DateUtils;
import com.jeeplus.common.config.Global;
import com.jeeplus.common.json.AjaxJson;
import com.jeeplus.core.persistence.Page;
import com.jeeplus.core.web.BaseController;
import com.jeeplus.common.utils.StringUtils;
import com.jeeplus.common.utils.excel.ExportExcel;
import com.jeeplus.common.utils.excel.ImportExcel;
import com.jeeplus.modules.tms.entity.Dispatch;
import com.jeeplus.modules.tms.service.DispatchService;

/**
 * 调度单Controller
 * @author dhw
 * @version 2017-11-29
 */
@Controller
@RequestMapping(value = "${adminPath}/tms/dispatch")
public class DispatchController extends BaseController {

	@Autowired
	private DispatchService dispatchService;

	@ModelAttribute
	public Dispatch get(@RequestParam(required=false) String id) {
		Dispatch entity = null;
		if (StringUtils.isNotBlank(id)){
			entity = dispatchService.get(id);
		}
		if (entity == null){
			entity = new Dispatch();
		}
		return entity;
	}


//			dispatchCarriers
//			dispatchDistance
//			dispatchDistribution
	/**
	 * 城配调度单列表页面
	 */
	@RequiresPermissions("tms:dispatch:list")
	@RequestMapping(value = {"dispatchDistributionList", ""})
	public String dispatchDistributionList() {
		return "modules/tms/dispatchDistributionList";
	}
	/**
	 * 长途调度单列表页面
	 */
	@RequiresPermissions("tms:dispatch:list")
	@RequestMapping(value = {"dispatchDistanceList", ""})
	public String dispatchDistanceList() {
		return "modules/tms/dispatchDistanceList";
	}
	/**
	 * 转承运商调度单列表页面
	 */
	@RequiresPermissions("tms:dispatch:list")
	@RequestMapping(value = {"dispatchCarriersList", ""})
	public String dispatchCarriersList() {
		return "modules/tms/dispatchCarriersList";
	}

	/**
	 * 城配调度单列表数据
	 */
	@ResponseBody
	@RequiresPermissions("tms:dispatch:list")
	@RequestMapping(value = "dispatchDistributionData")
	public Map<String, Object> dispatchDistributionData(Dispatch dispatch, HttpServletRequest request, HttpServletResponse response, Model model) {
		dispatch.setType("0");
		Page<Dispatch> page = dispatchService.findPage(new Page<Dispatch>(request, response), dispatch);
		return getBootstrapData(page);
	}
	/**
	 * 长途调度单列表数据
	 */
	@ResponseBody
	@RequiresPermissions("tms:dispatch:list")
	@RequestMapping(value = "dispatchDistanceData")
	public Map<String, Object> dispatchDistanceData(Dispatch dispatch, HttpServletRequest request, HttpServletResponse response, Model model) {
		dispatch.setType("1");
		Page<Dispatch> page = dispatchService.findPage(new Page<Dispatch>(request, response), dispatch);
		return getBootstrapData(page);
	}
	/**
	 * 转承运商调度单列表数据
	 */
	@ResponseBody
	@RequiresPermissions("tms:dispatch:list")
	@RequestMapping(value = "dispatchCarriersData")
	public Map<String, Object> dispatchCarriersData(Dispatch dispatch, HttpServletRequest request, HttpServletResponse response, Model model) {
		dispatch.setType("2");
		Page<Dispatch> page = dispatchService.findPage(new Page<Dispatch>(request, response), dispatch);
		return getBootstrapData(page);
	}
	/**
	 * 查看，增加，编辑 城配调度单表单页面
	 */
	@RequiresPermissions(value={"tms:dispatch:view","tms:dispatch:add","tms:dispatch:edit"},logical=Logical.OR)
	@RequestMapping(value = "distributionform")
	public String distributionform(Dispatch dispatch, Model model) {
		if (dispatch.getType()== null){
			dispatch.setType("0");
		}
		if (dispatch.getCode()==null){
			Random random = new Random();
			int rannum = (int)(random.nextDouble()*(999-100+1))+100;//获取三位随机数
			Date d = new Date();
			dispatch.setCode("40"+d.getTime()+rannum+"");
		}
		if (dispatch.getDispatchDDate()==null){
			dispatch.setDispatchDDate(new Date());
		}

		model.addAttribute("dispatch", dispatch);
		return "modules/tms/dispatchDistributionForm";
	}
	/**
	 * 查看，增加，编辑 长途调度单表单页面
	 */
	@RequiresPermissions(value={"tms:dispatch:view","tms:dispatch:add","tms:dispatch:edit"},logical=Logical.OR)
	@RequestMapping(value = "distanceform")
	public String distanceform(Dispatch dispatch, Model model) {
		if (dispatch.getType()== null){
			dispatch.setType("1");
		}
		if (dispatch.getCode()==null){
			Random random = new Random();
			int rannum = (int)(random.nextDouble()*(999-100+1))+100;//获取三位随机数
			Date d = new Date();
			dispatch.setCode("40"+d.getTime()+rannum+"");
		}
		if (dispatch.getDispatchDDate()==null){
			dispatch.setDispatchDDate(new Date());
		}

		model.addAttribute("dispatch", dispatch);
		return "modules/tms/dispatchDistanceForm";
	}


	/**
	 * 查看，增加，编辑 转承运商调度单表单页面
	 */
	@RequiresPermissions(value={"tms:dispatch:view","tms:dispatch:add","tms:dispatch:edit"},logical=Logical.OR)
	@RequestMapping(value = "carriersform")
	public String carriersform(Dispatch dispatch, Model model) {
		if (dispatch.getType()== null){
			dispatch.setType("2");
		}
		if (dispatch.getCode()==null){
			Random random = new Random();
			int rannum = (int)(random.nextDouble()*(999-100+1))+100;//获取三位随机数
			Date d = new Date();
			dispatch.setCode("40"+d.getTime()+rannum+"");
		}
		if (dispatch.getDispatchDDate()==null){
			dispatch.setDispatchDDate(new Date());
		}

		model.addAttribute("dispatch", dispatch);
		return "modules/tms/dispatchCarriersForm";
	}

	/**
	 * 保存调度单
	 */
	@ResponseBody
	@RequiresPermissions(value={"tms:dispatch:add","tms:dispatch:edit"},logical=Logical.OR)
	@RequestMapping(value = "save")
	public AjaxJson save(Dispatch dispatch, Model model, RedirectAttributes redirectAttributes) throws Exception{
		AjaxJson j = new AjaxJson();
		if (!beanValidator(model, dispatch)){
			j.setSuccess(false);
			j.setMsg("非法参数！");
			return j;
		}
		//新增或编辑表单保存
		dispatchService.save(dispatch);//保存
		j.setSuccess(true);
		j.setMsg("保存调度单成功");
		return j;
	}

	/**
	 * 删除调度单
	 */
	@ResponseBody
	@RequiresPermissions("tms:dispatch:del")
	@RequestMapping(value = "delete")
	public AjaxJson delete(Dispatch dispatch, RedirectAttributes redirectAttributes) {
		AjaxJson j = new AjaxJson();
		dispatchService.delete(dispatch);
		j.setMsg("删除调度单成功");
		return j;
	}

	/**
	 * 批量删除调度单
	 */
	@ResponseBody
	@RequiresPermissions("tms:dispatch:del")
	@RequestMapping(value = "deleteAll")
	public AjaxJson deleteAll(String ids, RedirectAttributes redirectAttributes) {
		AjaxJson j = new AjaxJson();
		String idArray[] =ids.split(",");
		for(String id : idArray){
			dispatchService.delete(dispatchService.get(id));
		}
		j.setMsg("删除调度单成功");
		return j;
	}

	/**
	 * 导出excel文件
	 */
	@ResponseBody
	@RequiresPermissions("tms:dispatch:export")
	@RequestMapping(value = "export", method=RequestMethod.POST)
	public AjaxJson exportFile(Dispatch dispatch, HttpServletRequest request, HttpServletResponse response, RedirectAttributes redirectAttributes) {
		AjaxJson j = new AjaxJson();
		try {
			String fileName = "调度单"+DateUtils.getDate("yyyyMMddHHmmss")+".xlsx";
			Page<Dispatch> page = dispatchService.findPage(new Page<Dispatch>(request, response, -1), dispatch);
			new ExportExcel("调度单", Dispatch.class).setDataList(page.getList()).write(response, fileName).dispose();
			j.setSuccess(true);
			j.setMsg("导出成功！");
			return j;
		} catch (Exception e) {
			j.setSuccess(false);
			j.setMsg("导出调度单记录失败！失败信息："+e.getMessage());
		}
		return j;
	}

	@ResponseBody
	@RequestMapping(value = "detail")
	public Dispatch detail(String id) {
		return dispatchService.get(id);
	}


	/**
	 * 导入Excel数据

	 */
	@RequiresPermissions("tms:dispatch:import")
	@RequestMapping(value = "import", method=RequestMethod.POST)
	public String importFile(MultipartFile file, RedirectAttributes redirectAttributes) {
		try {
			int successNum = 0;
			int failureNum = 0;
			StringBuilder failureMsg = new StringBuilder();
			ImportExcel ei = new ImportExcel(file, 1, 0);
			List<Dispatch> list = ei.getDataList(Dispatch.class);
			for (Dispatch dispatch : list){
				try{
					dispatchService.save(dispatch);
					successNum++;
				}catch(ConstraintViolationException ex){
					failureNum++;
				}catch (Exception ex) {
					failureNum++;
				}
			}
			if (failureNum>0){
				failureMsg.insert(0, "，失败 "+failureNum+" 条调度单记录。");
			}
			addMessage(redirectAttributes, "已成功导入 "+successNum+" 条调度单记录"+failureMsg);
		} catch (Exception e) {
			addMessage(redirectAttributes, "导入调度单失败！失败信息："+e.getMessage());
		}
		return "redirect:"+Global.getAdminPath()+"/tms/dispatch/?repage";
	}

	/**
	 * 下载导入调度单数据模板
	 */
	@RequiresPermissions("tms:dispatch:import")
	@RequestMapping(value = "import/template")
	public String importFileTemplate(HttpServletResponse response, RedirectAttributes redirectAttributes) {
		try {
			String fileName = "调度单数据导入模板.xlsx";
			List<Dispatch> list = Lists.newArrayList();
			new ExportExcel("调度单数据", Dispatch.class, 1).setDataList(list).write(response, fileName).dispose();
			return null;
		} catch (Exception e) {
			addMessage(redirectAttributes, "导入模板下载失败！失败信息："+e.getMessage());
		}
		return "redirect:"+Global.getAdminPath()+"/tms/dispatch/?repage";
	}


}